﻿// See https://aka.ms/new-console-template for more information
using Hyjx.GF.Database;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using MixerReport.Common;
using System.Diagnostics;

var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddLogging(options =>
{
    options.ClearProviders();
    options.AddEventLog(options =>
    {
        options.LogName = MixerReportConstants.EventLogName;
        options.SourceName = MixerReportConstants.EvenetLogClearDatabaseSourceName;
    });
});

if (!EventLog.Exists(MixerReportConstants.EventLogName) || !EventLog.SourceExists(MixerReportConstants.EvenetLogClearDatabaseSourceName))
    EventLog.CreateEventSource(MixerReportConstants.EvenetLogClearDatabaseSourceName, MixerReportConstants.EventLogName);

var host = builder.Build();

var logger = host.Services.GetService<ILogger<Program>>();

try
{
    string dbConnectionString = string.Empty;
    IConfigurationRoot con = new ConfigurationBuilder()
                .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                .AddJsonFile("DBsettings.json").Build();
    string? dbPath = con["GFDB:Path"];
    string? dbPassword = con["GFDB:Password"];
    if (string.IsNullOrEmpty(dbPath) || string.IsNullOrEmpty(dbPath))
        logger?.LogError("读取数据库配置失败");
    else
        dbConnectionString = $"Filename={dbPath};Password={dbPassword}";

    if (string.IsNullOrEmpty(dbConnectionString))
    {
        logger?.LogError("数据库连接字符串为空");
        return;
    }
    using GFDbContext db = new(dbConnectionString);
    db.Database.Migrate();

    IConfigurationRoot appCon = new ConfigurationBuilder()
                .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                .AddJsonFile("appsettings.json").Build();


    int keepDataDays = appCon.GetValue<int>("KeepDataDays");

    DateTime now = DateTime.Now;
    DateTime clearDate = now.AddDays(0 - keepDataDays);
    var query = db.MixerDataReports.Where(p => p.RecordTime < clearDate);

    int oneTimeDeleteRows = 5000;
    int logsCount = query.Count();

    if (logsCount > 0)
    {
        logger?.LogInformation(new EventId(1001), $"共有 {logsCount} 条数据需要删除");
        logger?.LogInformation(new EventId(1001), $"开始分段清除数据");
        decimal loopNumber = Math.Ceiling((decimal)logsCount / oneTimeDeleteRows); // 循环执行的次数
        int delTotal = 0;
        for (int i = 0; i < loopNumber; i++)
        {
            var delLogs = query.Take(oneTimeDeleteRows).ToArray();
            if (delLogs.Any())
            {
                db.MixerDataReports.RemoveRange(delLogs);
                db.SaveChanges();
            }
            logger?.LogInformation(new EventId(1001), $"已完成 {delLogs.Length} 条日志清除。");
            delTotal += delLogs.Length;
        }

        logger?.LogInformation(new EventId(1001), $"{clearDate} 之前的日志数据，共清除 {delTotal} 条。清除日志已完成。");
    }
    else
    {
        logger?.LogInformation(new EventId(1001), $"没有数据需要清除。");
    }
}
catch(Exception ex)
{
    logger?.LogError(new EventId(1001), ex, $"清除日志出错");
}
finally
{
    Environment.Exit(0);
}

//host.Run();